import { Context } from 'koa';
import { AppDataSource } from '@/config/database';
import { CustomerStoredValueCard } from '@/entities/basis/customer-stored-value-card.entity';
import { Customer } from '@/entities/basis/customer.entity';
import { CustomerPoints } from '@/entities/basis/customer-points.entity';
import { TokenPayload } from '@/utils/token.util';
import { PointsSourceType } from '@shared/constant/dataDictionary';

/**
 * 创建客户储值卡请求参数接口
 */
export interface ICreateStoredValueCardParams {
    /** 客户ID */
    customerId: string;
    /** 卡号 */
    cardNumber: string;
    /** 卡片名称 */
    cardName: string;
    /** 充值金额 */
    rechargeAmount: number;
    /** 赠送金额 */
    giftAmount?: number;
    /** 赠送积分 */
    giftPoints?: number;
    /** 有效期开始时间 */
    validFrom?: string;
    /** 有效期结束时间 */
    validTo?: string;
    /** 备注 */
    remark?: string;
}

/**
 * 生成积分批次号
 * @returns 格式：POINTS-YYYYMMDD-HHmmss-随机4位数字
 */
function generatePointsBatchNumber(): string {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    
    return `POINTS-${year}${month}${day}-${hours}${minutes}${seconds}-${random}`;
}

/**
 * 创建客户储值卡
 * @description 为指定客户创建新的储值卡，包含充值金额、赠送金额和积分等信息。如果有赠送积分，会同时创建积分记录
 * @param ctx - Koa上下文对象，包含储值卡创建参数
 * @returns 返回创建成功的储值卡信息
 * 
 * @example
 * POST /api/customers/stored-value-card/create
 * {
 *   "customerId": "customer-123",
 *   "cardNumber": "CARD001",
 *   "cardName": "VIP储值卡",
 *   "rechargeAmount": 100.00,
 *   "giftAmount": 20.00,
 *   "giftPoints": 50.00
 * }
 */
export async function createStoredValueCard(ctx: Context) {
    try {
        const params: ICreateStoredValueCardParams = ctx.request.body as ICreateStoredValueCardParams;
        const user: TokenPayload = ctx.state.user;

        // 参数校验
        if (!params.customerId || !params.cardNumber || !params.cardName || params.rechargeAmount === undefined) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '缺少必填参数：customerId, cardNumber, cardName, rechargeAmount'
            };
            return;
        }

        // 校验充值金额
        if (params.rechargeAmount <= 0) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '充值金额必须大于0'
            };
            return;
        }

        // 校验积分数量
        if (params.giftPoints !== undefined && params.giftPoints < 0) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '赠送积分不能为负数'
            };
            return;
        }

        // 校验有效期
        if (params.validFrom && params.validTo) {
            const fromDate = new Date(params.validFrom);
            const toDate = new Date(params.validTo);
            if (fromDate >= toDate) {
                ctx.status = 400;
                ctx.body = {
                    success: false,
                    message: '有效期开始时间必须早于结束时间'
                };
                return;
            }
        }

        // 使用事务处理储值卡创建和积分记录
        const result = await AppDataSource.transaction(async manager => {
            const customerRepository = manager.getRepository(Customer);
            const cardRepository = manager.getRepository(CustomerStoredValueCard);
            const pointsRepository = manager.getRepository(CustomerPoints);

            // 检查客户是否存在
            const customer = await customerRepository.findOne({
                where: { id: params.customerId }
            });

            if (!customer) {
                throw new Error('客户不存在');
            }

            // 检查卡号是否已存在
            const existingCard = await cardRepository.findOne({
                where: { cardNumber: params.cardNumber }
            });

            if (existingCard) {
                throw new Error('卡号已存在');
            }

            // 创建储值卡
            const storedValueCard = new CustomerStoredValueCard();
            storedValueCard.customerId = params.customerId;
            storedValueCard.cardNumber = params.cardNumber;
            storedValueCard.cardName = params.cardName;
            storedValueCard.rechargeAmount = params.rechargeAmount;
            storedValueCard.giftAmount = params.giftAmount || 0;
            storedValueCard.giftPoints = params.giftPoints || 0;
            // 当前余额 = 充值金额 + 赠送金额
            storedValueCard.currentBalance = params.rechargeAmount + (params.giftAmount || 0);
            storedValueCard.validFrom = params.validFrom ? new Date(params.validFrom) : undefined;
            storedValueCard.validTo = params.validTo ? new Date(params.validTo) : undefined;
            storedValueCard.remark = params.remark;
            storedValueCard.createdBy = user.id;
            storedValueCard.updatedBy = user.id;

            const savedCard = await cardRepository.save(storedValueCard);

            // 如果有赠送积分，创建积分记录
            let pointsRecord = null;
            if (params.giftPoints && params.giftPoints > 0) {
                const customerPoints = new CustomerPoints();
                customerPoints.customerId = params.customerId;
                customerPoints.batchNumber = generatePointsBatchNumber();
                customerPoints.pointsAmount = params.giftPoints;
                customerPoints.remainingPoints = params.giftPoints;
                customerPoints.sourceType = PointsSourceType.RECHARGE_GIFT;
                customerPoints.sourceDescription = `储值卡充值赠送积分 - 卡号：${params.cardNumber}`;
                customerPoints.validFrom = params.validFrom ? new Date(params.validFrom) : new Date();
                customerPoints.validTo = params.validTo ? new Date(params.validTo) : undefined;
                customerPoints.status = 'active';
                customerPoints.remark = `储值卡${params.cardNumber}充值${params.rechargeAmount}元赠送积分`;
                customerPoints.createdBy = user.id;
                customerPoints.updatedBy = user.id;

                pointsRecord = await pointsRepository.save(customerPoints);

                // 更新客户的积分余额
                customer.currentPoints = (Number(customer.currentPoints) || 0) + params.giftPoints;
                await customerRepository.save(customer);
            }

            return {
                card: savedCard,
                points: pointsRecord
            };
        });

        ctx.status = 201;
        ctx.body = {
            success: true,
            message: '储值卡创建成功' + (result.points ? '，积分已发放' : ''),
            data: {
                card: result.card,
                points: result.points
            }
        };

    } catch (error) {
        console.error('创建储值卡失败:', error);
        
        // 根据错误类型返回不同的状态码
        if (error.message === '客户不存在') {
            ctx.status = 404;
            ctx.body = {
                success: false,
                message: '客户不存在'
            };
        } else if (error.message === '卡号已存在') {
            ctx.status = 409;
            ctx.body = {
                success: false,
                message: '卡号已存在'
            };
        } else {
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '服务器内部错误'
            };
        }
    }
} 